package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yu.crm.domain.pojo.CrmRole;
import com.yu.crm.domain.pojo.CrmRoleGroup;
import com.yu.crm.mapper.CrmRoleGroupMapper;
import com.yu.crm.service.CrmRoleGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ExceptionHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 角色分组表 服务实现类
 * </p>
 *
 * @author donnie-bin
 * @since 2019-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmRoleGroupServiceImpl extends ServiceImpl<CrmRoleGroupMapper, CrmRoleGroup> implements CrmRoleGroupService {

    @Override
    public boolean saveOrUpdate(CrmRoleGroup entity) {
        if(DataHelpers.isEmpty(entity.getId())){
            QueryWrapper<CrmRoleGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pid", entity.getPid());
            queryWrapper.eq("role_group_name", entity.getRoleGroupName());
            int oldCount = super.count(queryWrapper);
            ValidatorHelpers.validateDataExist("分组名称不能重复", oldCount);
            if (DataHelpers.isEmpty(entity.getPid())) {
                entity.setPid((long) 0);
            }
            entity.setGmtCreate(DateHelpers.now());
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.save(entity),"新增失败");
        }else{
            entity.setGmtModified(DateHelpers.now());
            return ExceptionHelpers.checkData(super.updateById(entity),"更新失败");
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        return ExceptionHelpers.checkData(super.removeById(id), "删除失败");
    }

    @Override
    public List<CrmRoleGroup> treeList(Long pid) {
        return baseMapper.getChildren(pid);
    }

}
